<script setup lang="ts">
import { ref, watch, computed } from 'vue';
import { createCourseSubjects } from '@/api/classroom';
import { getSubjectList } from '@/api/subject';
import { showToast, showSuccessToast } from 'vant';
import type { Subject } from '@/api/subject/type';
import { router } from '@/router';

const props = defineProps({
  show: {
    type: Boolean,
    default: false
  },
  courseId: {
    type: String,
    required: true
  },
  type: {
    type: String,
    required: true,
    validator: (value: string) => ['EXAM', 'HOMEWORK'].includes(value)
  },
  title: {
    type: String,
    default: '添加'
  }
});

const emit = defineEmits(['update:show', 'created']);

const visible = ref(props.show);
const subjects = ref<Subject[]>([]);
const selectedSubject = ref('');
const startDateInput = ref(''); // 开始日期输入
const startTimeInput = ref(''); // 开始时间输入
const endDateInput = ref('');   // 结束日期输入
const endTimeInput = ref('');   // 结束时间输入
const startTime = ref('');      // 最终的开始时间ISO字符串
const endTime = ref('');        // 最终的结束时间ISO字符串
const loading = ref(false);
const submitting = ref(false);

const startDateValid = ref(true);
const startTimeValid = ref(true);
const endDateValid = ref(true);
const endTimeValid = ref(true);

const startDateError = ref('');
const startTimeError = ref('');
const endDateError = ref('');
const endTimeError = ref('');

// 日期格式验证正则 (yyyy-MM-dd)
const dateRegex = /^(\d{4})-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])$/;
// 时间格式验证正则 (HH:mm)
const timeRegex = /^([01]\d|2[0-3]):([0-5]\d)$/;

const submitActive = computed(() => {
  return (
    selectedSubject.value &&
    startDateValid.value && startTimeValid.value &&
    endDateValid.value && endTimeValid.value &&
    startTime.value && endTime.value
  );
});

const getCurrentDateStr = () => {
  const now = new Date();
  return `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')}`;
};

const getCurrentTimeStr = () => {
  const now = new Date();
  const minutes = Math.ceil(now.getMinutes() / 5) * 5;
  const hours = minutes === 60 ? now.getHours() + 1 : now.getHours();
  return `${String(hours % 24).padStart(2, '0')}:${String(minutes % 60).padStart(2, '0')}`;
};

const getDefaultEndDateStr = (isExam = false) => {
  const now = new Date();
  if (isExam) {
    return getCurrentDateStr();
  } else {
    const tomorrow = new Date(now);
    tomorrow.setDate(now.getDate() + 1);
    return `${tomorrow.getFullYear()}-${String(tomorrow.getMonth() + 1).padStart(2, '0')}-${String(tomorrow.getDate()).padStart(2, '0')}`;
  }
};

const getDefaultEndTimeStr = (isExam = false) => {
  const now = new Date();
  let hours = now.getHours();
  let minutes = Math.ceil(now.getMinutes() / 5) * 5;
  
  if (isExam) {
    hours = (hours + 2) % 24;
  } else {
    hours = 23;
    minutes = 55;
  }
  
  return `${String(hours).padStart(2, '0')}:${String(minutes % 60).padStart(2, '0')}`;
};

const combineDateTime = (dateStr: string, timeStr: string): string => {
  if (!dateStr || !timeStr) return '';
  if (!dateRegex.test(dateStr) || !timeRegex.test(timeStr)) return '';
  
  try {
    const [hours, minutes] = timeStr.split(':');
    const combinedDate = new Date(dateStr);
    combinedDate.setHours(parseInt(hours, 10), parseInt(minutes, 10), 0, 0);
    return combinedDate.toISOString();
  } catch (e) {
    console.error('日期时间格式错误:', e);
    return '';
  }
};

const validateStartDate = () => {
  if (!startDateInput.value) {
    startDateValid.value = false;
    startDateError.value = '请输入开始日期';
    return false;
  }
  
  if (!dateRegex.test(startDateInput.value)) {
    startDateValid.value = false;
    startDateError.value = '日期格式不正确，请使用 yyyy-MM-dd 格式';
    return false;
  }
  
  try {
    const date = new Date(startDateInput.value);
    if (isNaN(date.getTime())) {
      startDateValid.value = false;
      startDateError.value = '无效的日期';
      return false;
    }
    
    const now = new Date();
    now.setHours(0, 0, 0, 0);
    const startDate = new Date(startDateInput.value);
    startDate.setHours(0, 0, 0, 0);
    
    if (startDate < now) {
      startDateValid.value = false;
      startDateError.value = '开始日期不能早于今天';
      return false;
    }
  } catch (e) {
    startDateValid.value = false;
    startDateError.value = '日期解析错误';
    return false;
  }
  
  startDateValid.value = true;
  startDateError.value = '';
  return true;
};

const validateStartTime = () => {
  if (!startTimeInput.value) {
    startTimeValid.value = false;
    startTimeError.value = '请输入开始时间';
    return false;
  }
  
  if (!timeRegex.test(startTimeInput.value)) {
    startTimeValid.value = false;
    startTimeError.value = '时间格式不正确，请使用 HH:mm 格式';
    return false;
  }
  
  try {
    const now = new Date();
    const today = getCurrentDateStr();
    const startDate = new Date(startDateInput.value || today);
    const [hours, minutes] = startTimeInput.value.split(':').map(Number);
    startDate.setHours(hours, minutes, 0, 0);
    
    if (startDateInput.value === getCurrentDateStr() && startDate < now) {
      startTimeValid.value = false;
      startTimeError.value = '开始时间不能早于当前时间';
      return false;
    }
  } catch (e) {
    startTimeValid.value = false;
    startTimeError.value = '时间解析错误';
    return false;
  }
  
  startTimeValid.value = true;
  startTimeError.value = '';
  return true;
};

const validateEndDate = () => {
  if (!endDateInput.value) {
    endDateValid.value = false;
    endDateError.value = '请输入结束日期';
    return false;
  }
  
  if (!dateRegex.test(endDateInput.value)) {
    endDateValid.value = false;
    endDateError.value = '日期格式不正确，请使用 yyyy-MM-dd 格式';
    return false;
  }
  
  try {
    const date = new Date(endDateInput.value);
    if (isNaN(date.getTime())) {
      endDateValid.value = false;
      endDateError.value = '无效的日期';
      return false;
    }
    
    const now = new Date();
    now.setHours(0, 0, 0, 0);
    const endDate = new Date(endDateInput.value);
    endDate.setHours(0, 0, 0, 0);
    
    if (endDate < now) {
      endDateValid.value = false;
      endDateError.value = '结束日期不能早于今天';
      return false;
    }
    
    if (startDateInput.value) {
      const startDate = new Date(startDateInput.value);
      startDate.setHours(0, 0, 0, 0);
      
      if (endDate < startDate) {
        endDateValid.value = false;
        endDateError.value = '结束日期不能早于开始日期';
        return false;
      }
    }
  } catch (e) {
    endDateValid.value = false;
    endDateError.value = '日期解析错误';
    return false;
  }
  
  endDateValid.value = true;
  endDateError.value = '';
  return true;
};

const validateEndTime = () => {
  if (!endTimeInput.value) {
    endTimeValid.value = false;
    endTimeError.value = '请输入结束时间';
    return false;
  }
  
  if (!timeRegex.test(endTimeInput.value)) {
    endTimeValid.value = false;
    endTimeError.value = '时间格式不正确，请使用 HH:mm 格式';
    return false;
  }
  
  try {
    if (startDateInput.value && endDateInput.value && startDateInput.value === endDateInput.value && startTimeInput.value) {
      const [startHours, startMinutes] = startTimeInput.value.split(':').map(Number);
      const [endHours, endMinutes] = endTimeInput.value.split(':').map(Number);
      
      if (endHours < startHours || (endHours === startHours && endMinutes <= startMinutes)) {
        endTimeValid.value = false;
        endTimeError.value = '结束时间必须晚于开始时间';
        return false;
      }
    }
  } catch (e) {
    endTimeValid.value = false;
    endTimeError.value = '时间解析错误';
    return false;
  }
  
  endTimeValid.value = true;
  endTimeError.value = '';
  return true;
};

const validateAndUpdateTimes = () => {
  const startDateIsValid = validateStartDate();
  const startTimeIsValid = validateStartTime();
  const endDateIsValid = validateEndDate();
  const endTimeIsValid = validateEndTime();
  
  if (startDateIsValid && startTimeIsValid) {
    startTime.value = combineDateTime(startDateInput.value, startTimeInput.value);
  } else {
    startTime.value = '';
  }
  
  if (endDateIsValid && endTimeIsValid) {
    endTime.value = combineDateTime(endDateInput.value, endTimeInput.value);
  } else {
    endTime.value = '';
  }
  
  return startDateIsValid && startTimeIsValid && endDateIsValid && endTimeIsValid;
};

watch([startDateInput, startTimeInput], () => {
  validateStartDate();
  validateStartTime();
  validateAndUpdateTimes();
});

watch([endDateInput, endTimeInput], () => {
  validateEndDate();
  validateEndTime();
  validateAndUpdateTimes();
});

watch(() => props.show, (newVal) => {
  visible.value = newVal;
  if (newVal) {
    fetchSubjects();
    
    const currentDate = getCurrentDateStr();
    const currentTime = getCurrentTimeStr();
    const isExam = props.type === 'EXAM';
    
    startDateInput.value = currentDate;
    startTimeInput.value = currentTime;
    
    endDateInput.value = getDefaultEndDateStr(isExam);
    endTimeInput.value = getDefaultEndTimeStr(isExam);
    
    validateAndUpdateTimes();
  }
});

watch(() => visible.value, (newVal) => {
  emit('update:show', newVal);
});

const fetchSubjects = async () => {
  try {
    loading.value = true;
    const res = await getSubjectList();
    if (res && res.data) {
      subjects.value = res.data;
    }
  } catch (error) {
    showToast('获取题目集列表失败');
    console.error('获取题目集列表失败:', error);
  } finally {
    loading.value = false;
  }
};

const closeModal = () => {
  resetForm();
  visible.value = false;
};

const resetForm = () => {
  selectedSubject.value = '';
  startDateInput.value = '';
  startTimeInput.value = '';
  endDateInput.value = '';
  endTimeInput.value = '';
  startTime.value = '';
  endTime.value = '';
  
  startDateValid.value = true;
  startTimeValid.value = true;
  endDateValid.value = true;
  endTimeValid.value = true;
  
  startDateError.value = '';
  startTimeError.value = '';
  endDateError.value = '';
  endTimeError.value = '';
};

const handleSubmit = async () => {
  if (!selectedSubject.value) {
    return showToast('请选择题目集');
  }
  
  if (!validateAndUpdateTimes()) {
    if (!startDateValid.value) {
      return showToast(startDateError.value);
    }
    if (!startTimeValid.value) {
      return showToast(startTimeError.value);
    }
    if (!endDateValid.value) {
      return showToast(endDateError.value);
    }
    if (!endTimeValid.value) {
      return showToast(endTimeError.value);
    }
    return;
  }
  
  if (new Date(startTime.value) >= new Date(endTime.value)) {
    return showToast('结束时间必须晚于开始时间');
  }
  
  const data = {
    courseId: props.courseId,
    subjectId: selectedSubject.value,
    type: props.type,
    status: 'ACTIVE',
    startTime: startTime.value,
    endTime: endTime.value
  };
  
  try {
    submitting.value = true;
    await createCourseSubjects(data);
    showSuccessToast('添加成功');
    emit('created');
    closeModal();
  } catch (error) {
    showToast('添加失败');
    console.error('添加失败:', error);
  } finally {
    submitting.value = false;
  }
};

const createNewSubject = () => {
  router.push('/subject/create');
  
  // 先保存当前状态，在创建完题目后返回
  localStorage.setItem('returnPath', router.currentRoute.value.fullPath);
  
};
</script>

<template>
  <van-popup v-model:show="visible" position="bottom" round closeable :close-on-click-overlay="false" :style="{ height: '90%' }">
    <div class="modal-container">
      <div class="modal-header">
        <h3 class="modal-title">
          {{ title }} {{ props.type === 'EXAM' ? '考试' : '作业' }}
        </h3>
      </div>
      
      <div class="modal-content">
        <van-form @submit="handleSubmit">
          <van-cell-group inset>
            <van-field
              v-model="selectedSubject"
              is-link
              readonly
              name="subject"
              label="选择题目集"
              placeholder="点击选择题目集"
              :rules="[{ required: true, message: '请选择题目集' }]"
              @click="() => {}"
            >
              <template #button>
                <van-button size="small" type="primary" plain @click.stop="createNewSubject">
                  新建题目集
                </van-button>
              </template>
            </van-field>
            
            <div class="subject-list" v-if="!loading && subjects.length > 0">
              <van-radio-group v-model="selectedSubject">
                <van-cell v-for="subject in subjects" :key="subject.id">
                  <template #title>
                    <div class="subject-item">
                      <van-image
                        :src="subject.avatar"
                        width="40"
                        height="40"
                        radius="4"
                        fit="cover"
                      />
                      <div class="subject-info">
                        {{ subject.name }}
                      </div>
                    </div>
                  </template>
                  <template #right-icon>
                    <van-radio :name="subject.id" />
                  </template>
                </van-cell>
              </van-radio-group>
            </div>
            <van-empty v-else-if="!loading && subjects.length === 0" description="暂无题目集" />
            <div class="loading-container" v-else>
              <van-loading type="spinner" size="24px">加载中...</van-loading>
            </div>
            
            <van-field
              v-model="startDateInput"
              name="startDate"
              label="开始日期"
              placeholder="输入开始日期，如 2023-10-25"
              :error="!startDateValid"
              :error-message="startDateError"
              @blur="validateStartDate"
            />
            
            <van-field
              v-model="startTimeInput"
              name="startTime"
              label="开始时间"
              placeholder="输入开始时间，如 14:30"
              :error="!startTimeValid"
              :error-message="startTimeError"
              @blur="validateStartTime"
            />
            
            <van-field
              v-model="endDateInput"
              name="endDate"
              label="结束日期"
              placeholder="输入结束日期，如 2023-10-26"
              :error="!endDateValid"
              :error-message="endDateError"
              @blur="validateEndDate"
            />
            
            <van-field
              v-model="endTimeInput"
              name="endTime"
              label="结束时间"
              placeholder="输入结束时间，如 14:30"
              :error="!endTimeValid"
              :error-message="endTimeError"
              @blur="validateEndTime"
            />
            
            <div class="time-hint">
              <p class="hint-text">
                <van-icon name="info-o" color="#1989fa" /> 提示：
                <br>- 日期格式：yyyy-MM-dd，例如 2023-10-25
                <br>- 时间格式：HH:mm（24小时制），例如 14:30
                <br>- 结束时间必须晚于开始时间
                <br>- 开始时间必须晚于当前时间
                <br>- {{ props.type === 'EXAM' ? '考试时间建议设置为2小时' : '作业建议设置合理的截止日期' }}
              </p>
            </div>
          </van-cell-group>
          
          <div class="submit-buttons">
            <van-button 
              round 
              block 
              type="primary" 
              native-type="submit" 
              :loading="submitting"
              :disabled="!submitActive"
              :class="{ 'button-active': submitActive }"
            >
              确认添加
            </van-button>
            <van-button round block plain type="default" @click="closeModal" class="cancel-btn">
              取消
            </van-button>
          </div>
        </van-form>
      </div>
    </div>
  </van-popup>
</template>

<style lang="scss" scoped>
.modal-container {
  display: flex;
  flex-direction: column;
  height: 90%;
  padding: 16px;
  overflow: hidden;
  
  .modal-header {
    padding-bottom: 16px;
    border-bottom: 1px solid #f2f2f2;
    margin-bottom: 16px;
    flex-shrink: 0;
    
    .modal-title {
      text-align: center;
      margin: 0;
      font-size: 18px;
      font-weight: 500;
    }
  }
  
  .modal-content {
    flex: 1;
    overflow-y: auto;
    scrollbar-width: none;
    -ms-overflow-style: none;
    
    &::-webkit-scrollbar {
      display: none;
    }
    
    .subject-list {
      max-height: 110px;
      overflow-y: auto;
      scrollbar-width: thin;
      
      &::-webkit-scrollbar {
        width: 4px;
      }
      
      &::-webkit-scrollbar-track {
        background: #f1f1f1;
        border-radius: 2px;
      }
      
      &::-webkit-scrollbar-thumb {
        background: #ccc;
        border-radius: 2px;
      }
      
      &::-webkit-scrollbar-thumb:hover {
        background: #999;
      }
      
      .subject-item {
        display: flex;
        align-items: center;
        
        .subject-info {
          margin-left: 12px;
          font-size: 14px;
        }
      }
    }
    
    .loading-container {
      display: flex;
      justify-content: center;
      padding: 20px 0;
    }
    
    .time-hint {
      margin-top: 12px;
      padding: 8px 12px;
      border-radius: 4px;
      background-color: #f5f7fa;
      
      .hint-text {
        color: #666;
        font-size: 13px;
        line-height: 1.5;
        margin: 0;
      }
    }
    
    .submit-buttons {
      margin-top: 16px;
      
      .button-active {
        background-color: #1989fa;
        color: white;
        font-weight: bold;
        transition: all 0.3s;
      }
      
      .cancel-btn {
        margin-top: 12px;
      }
    }
  }
}
</style>
